<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!-- 左侧：分区树 -->
            <el-col :span="6">
                <el-card class="partition-tree-card">
                    <template #header>
                        <div class="card-header">
                            <span>分区列表</span>
                            <div>
                                <el-button type="primary" size="small" @click="handleAddPartition">新增分区</el-button>
                                <el-button size="small" @click="refreshPartitionTree">刷新</el-button>
                            </div>
                        </div>
                    </template>

                    <!-- <el-input v-model="partitionSearch" placeholder="搜索分区" clearable prefix-icon="Search"
                        class="mb-2" /> -->

                    <el-scrollbar height="560px">
                        <el-tree ref="partitionTreeRef" :data="partitionTree" :props="treeProps" node-key="siteZoneId"
                            :expand-on-click-node="false" :filter-node-method="filterPartitionNode"
                            @node-click="handlePartitionSelect">
                            <template #default="{ node, data }">
                                <div class="custom-tree-node">
                                    <div class="node-content">
                                        <span class="zone-name">{{ data.zoneName }}</span>
                                        <span class="site-count" v-if="data.siteCount > 0">({{ data.siteCount }})</span>
                                    </div>
                                    <div class="node-actions">
                                        <el-button link type="primary" size="small"
                                            @click.stop="handleEditPartition(data)">
                                            <el-icon>
                                                <Edit />
                                            </el-icon>
                                        </el-button>
                                        <el-button link type="danger" size="small"
                                            @click.stop="handleDeletePartition(data)">
                                            <el-icon>
                                                <Delete />
                                            </el-icon>
                                        </el-button>
                                    </div>
                                </div>
                            </template>
                        </el-tree>
                    </el-scrollbar>
                </el-card>
            </el-col>

            <!-- 右侧：站点关联管理 -->
            <el-col :span="18">
                <el-card v-if="activePartition" class="site-association-card">
                    <template #header>
                        <div class="card-header">
                            <span>站点关联管理 - {{ activePartition.zoneName }}</span>
                            <el-button type="primary" size="small" @click="handleSaveSort">保存排序</el-button>
                        </div>
                    </template>

                    <!-- 分区基本信息 -->
                    <div class="config-section">
                        <h3 class="section-title mb-2">分区信息</h3>
                        <el-descriptions :column="2" border>
                            <el-descriptions-item label="分区ID">{{ activePartition.siteZoneId }}</el-descriptions-item>
                            <el-descriptions-item label="分区名称">{{ activePartition.zoneName }}</el-descriptions-item>
                            <el-descriptions-item label="父分区ID">{{ activePartition.parentZoneId || '根分区'
                                }}</el-descriptions-item>
                            <el-descriptions-item label="关联站点数">
                                <el-tag>{{ relatedSites.length }}</el-tag>
                            </el-descriptions-item>
                        </el-descriptions>
                    </div>

                    <!-- 已关联站点 -->
                    <div class="config-section">
                        <div class="section-header">
                            <h3 class="section-title">已关联站点 ({{ relatedSites.length }})</h3>
                            <el-button type="primary" size="small" @click="handleAddSite">关联站点</el-button>
                        </div>

                        <el-table :data="relatedSites" border v-loading="loading" row-key="siteId"
                            @selection-change="handleSelectionChange">
                            <el-table-column type="selection" width="55" align="center" />
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="siteName" label="站点名称" align="center" />
                            <el-table-column prop="sort" label="排序值" align="center" width="120">
                                <template #default="{ row, $index }">
                                    <el-input-number v-model="row.sort" :min="0" controls-position="right" size="small"
                                        @change="handleSortChange(row, $index)" />
                                </template>
                            </el-table-column>
                            <el-table-column label="操作" width="120" align="center">
                                <template #default="{ row }">
                                    <el-button size="small" type="danger" @click="handleRemoveSite(row)">移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <!-- 未关联站点 -->
                    <div class="config-section" v-if="unrelatedSites.length > 0">
                        <div class="section-header">
                            <h3 class="section-title">可关联站点 ({{ unrelatedSites.length }})</h3>
                        </div>

                        <el-table :data="unrelatedSites" border>
                            <el-table-column type="index" label="序号" width="60" align="center" />
                            <el-table-column prop="siteName" label="站点名称" align="center" />
                            <el-table-column label="操作" width="100" align="center">
                                <template #default="{ row }">
                                    <el-button size="small" type="primary"
                                        @click="handleAssociateSite(row)">关联</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </el-card>

                <!-- 空状态 -->
                <el-card v-else class="empty-card">
                    <el-empty description="请从左侧选择一个分区进行管理" />
                </el-card>
            </el-col>
        </el-row>

        <!-- 新增/编辑分区对话框 -->
        <el-dialog v-model="partitionDialog.visible" :title="partitionDialog.title" width="500px">
            <el-form ref="partitionFormRef" :model="partitionForm" :rules="partitionRules" label-width="80px">
                <el-form-item label="分区名称" prop="zoneName">
                    <el-input v-model="partitionForm.zoneName" placeholder="请输入分区名称" />
                </el-form-item>
                <el-form-item label="父分区" prop="parentZoneId">
                    <el-tree-select v-model="partitionForm.parentZoneId" :data="partitionTree" :props="treeProps"
                        check-strictly node-key="siteZoneId" :render-after-expand="false" placeholder="请选择父分区"
                        style="width: 100%" />
                </el-form-item>
                <el-form-item label="边界信息">
                    <el-input v-model="partitionForm.boundaryPoints" type="textarea" :rows="3"
                        placeholder="请输入边界信息(JSON格式)" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="partitionDialog.visible = false">取消</el-button>
                <el-button type="primary" @click="savePartition">保存</el-button>
            </template>
        </el-dialog>

        <!-- 关联站点对话框 -->
        <el-dialog v-model="siteDialog.visible" title="关联站点" width="800px">
            <div class="dialog-content">
                <el-table :data="unrelatedSites" border @selection-change="handleSiteSelectionChange">
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column type="index" label="序号" width="60" align="center" />
                    <el-table-column prop="siteName" label="站点名称" align="center" />
                    <el-table-column prop="siteCode" label="站点编号" align="center" />
                    <el-table-column prop="siteType" label="站点类型" align="center" />
                </el-table>

                <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
                    <el-button @click="siteDialog.visible = false">取消</el-button>
                    <el-button type="primary" @click="batchAssociateSites">确认关联</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, Delete } from '@element-plus/icons-vue'

// API接口
import {
    getPartitionList,
    getRelatedSiteList,
    getUnrelatedSiteList,
    addSiteAssociation,
    deleteSiteAssociation,
    addPartition,
    updatePartition,
    deletePartition,
    saveSiteSort
} from '@/api/dispatch/affair/distpachArea'

// 响应式数据
const partitionSearch = ref('')
const activePartition = ref(null)
const loading = ref(false)
const selectedSites = ref([])
const selectedUnrelatedSites = ref([])

// 树形数据
const partitionTree = ref([])
const partitionTreeRef = ref()
const treeProps = {
    children: 'childNode',
    label: 'zoneName'
}

// 站点数据
const relatedSites = ref([])
const unrelatedSites = ref([])

// 对话框控制
const partitionDialog = reactive({
    visible: false,
    title: '新增分区'
})

const siteDialog = reactive({
    visible: false
})

// 表单数据
const partitionForm = reactive({
    siteZoneId: null,
    parentZoneId: 0,
    zoneName: '',
    boundaryPoints: ''
})

// 表单验证规则
const partitionRules = reactive({
    zoneName: [
        { required: true, message: '请输入分区名称', trigger: 'blur' }
    ]
})

// 初始化
onMounted(() => {
    loadPartitionTree()
})

// 加载分区树
const loadPartitionTree = async () => {
    try {
        loading.value = true
        const res = await getPartitionList()
        partitionTree.value = res.data || []

        // 为每个节点添加站点数量统计
        const countSites = async (node) => {
            if (node.siteZoneId) {
                const sitesRes = await getRelatedSiteList(node.siteZoneId)
                node.siteCount = sitesRes.data?.length || 0
            }
            if (node.childNode && node.childNode.length > 0) {
                for (const child of node.childNode) {
                    await countSites(child)
                }
            }
        }

        for (const node of partitionTree.value) {
            await countSites(node)
        }
    } catch (error) {
        console.error('加载分区树失败:', error)
        ElMessage.error('加载分区树失败')
    } finally {
        loading.value = false
    }
}

// 分区搜索
const filterPartitionNode = (value, data) => {
    if (!value) return true
    return data.zoneName.includes(value)
}

// 选择分区
const handlePartitionSelect = async (data) => {
    activePartition.value = data
    await loadRelatedSites(data.siteZoneId)
    await loadUnrelatedSites(data.siteZoneId)
}

// 加载已关联站点
const loadRelatedSites = async (siteZoneId) => {
    try {
        loading.value = true
        const res = await getRelatedSiteList(siteZoneId)
        relatedSites.value = res.data || []
    } catch (error) {
        console.error('加载关联站点失败:', error)
        ElMessage.error('加载关联站点失败')
    } finally {
        loading.value = false
    }
}

// 加载未关联站点
const loadUnrelatedSites = async (siteZoneId) => {
    try {
        const res = await getUnrelatedSiteList()
        unrelatedSites.value = res.data || []
    } catch (error) {
        console.error('加载未关联站点失败:', error)
        ElMessage.error('加载未关联站点失败')
    }
}

// 新增分区
const handleAddPartition = () => {
    partitionDialog.title = '新增分区'
    partitionDialog.visible = true
    resetPartitionForm()
}

// 编辑分区
const handleEditPartition = (data) => {
    partitionDialog.title = '编辑分区'
    partitionDialog.visible = true
    Object.assign(partitionForm, data)
}

// 删除分区
const handleDeletePartition = async (data) => {
    try {
        await ElMessageBox.confirm(`确定删除分区 "${data.zoneName}" 吗？`, '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        await deletePartition([data.siteZoneId])
        ElMessage.success('删除成功')
        await loadPartitionTree()

        // 如果删除的是当前选中的分区，清空右侧内容
        if (activePartition.value?.siteZoneId === data.siteZoneId) {
            activePartition.value = null
            relatedSites.value = []
            unrelatedSites.value = []
        }
    } catch {
        // 用户取消删除
    }
}

// 保存分区
const savePartition = async () => {
    try {
        if (partitionForm.siteZoneId) {
            await updatePartition(partitionForm)
        } else {
            await addPartition(partitionForm)
        }

        ElMessage.success('保存成功')
        partitionDialog.visible = false
        await loadPartitionTree()
    } catch (error) {
        console.error('保存分区失败:', error)
        ElMessage.error('保存分区失败')
    }
}

// 关联站点
const handleAddSite = () => {
    siteDialog.visible = true
}

// 批量关联站点
const batchAssociateSites = async () => {
    try {
        if (selectedUnrelatedSites.value.length === 0) {
            ElMessage.warning('请选择要关联的站点')
            return
        }

        for (const site of selectedUnrelatedSites.value) {
            await addSiteAssociation(activePartition.value.siteZoneId, site.siteId)
        }

        ElMessage.success('关联成功')
        siteDialog.visible = false
        await loadRelatedSites(activePartition.value.siteZoneId)
        await loadUnrelatedSites(activePartition.value.siteZoneId)
        await loadPartitionTree() // 刷新站点数量
    } catch (error) {
        console.error('关联站点失败:', error)
        ElMessage.error('关联站点失败')
    }
}

// 单个关联站点
const handleAssociateSite = async (site) => {
    try {
        await addSiteAssociation(activePartition.value.siteZoneId, site.siteId)
        ElMessage.success('关联成功')
        await loadRelatedSites(activePartition.value.siteZoneId)
        await loadUnrelatedSites(activePartition.value.siteZoneId)
        await loadPartitionTree() // 刷新站点数量
    } catch (error) {
        console.error('关联站点失败:', error)
        ElMessage.error('关联站点失败')
    }
}

// 移除站点关联
const handleRemoveSite = async (site) => {
    try {
        await ElMessageBox.confirm(`确定从分区移除站点 "${site.siteName}" 吗？`, '提示', {
            type: 'warning',
            confirmButtonText: '确定',
            cancelButtonText: '取消'
        })

        await deleteSiteAssociation(activePartition.value.siteZoneId, site.siteId)
        ElMessage.success('移除成功')
        await loadRelatedSites(activePartition.value.siteZoneId)
        await loadUnrelatedSites(activePartition.value.siteZoneId)
        await loadPartitionTree() // 刷新站点数量
    } catch {
        // 用户取消
    }
}

// 保存排序
const handleSaveSort = async () => {
    try {
        const sortData = relatedSites.value.map((site, index) => ({
            siteId: site.siteId,
            siteZoneId: activePartition.value.siteZoneId,
            siteName: site.siteName,
            sort: site.sort || index
        }))

        await saveSiteSort(sortData)
        ElMessage.success('排序保存成功')
    } catch (error) {
        console.error('保存排序失败:', error)
        ElMessage.error('保存排序失败')
    }
}

// 排序变化处理
const handleSortChange = (row, index) => {
    // 可以添加实时保存或标记为脏数据
    console.log('排序变化:', row.siteName, row.sort)
}

// 选择变化
const handleSelectionChange = (selection) => {
    selectedSites.value = selection
}

const handleSiteSelectionChange = (selection) => {
    selectedUnrelatedSites.value = selection
}

// 刷新分区树
const refreshPartitionTree = () => {
    loadPartitionTree()
    if (activePartition.value) {
        loadRelatedSites(activePartition.value.siteZoneId)
        loadUnrelatedSites(activePartition.value.siteZoneId)
    }
}

// 重置表单
const resetPartitionForm = () => {
    Object.assign(partitionForm, {
        siteZoneId: null,
        parentZoneId: 0,
        zoneName: '',
        boundaryPoints: ''
    })
}
</script>

<style scoped>
.breadcrumb {
    margin-bottom: 20px;
    padding: 16px;
    background: white;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.partition-tree-card,
.site-association-card {
    height: 100%;
    min-height: 700px;
}

.empty-card {
    height: 700px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding: 5px 0;
}

.node-content {
    display: flex;
    align-items: center;
}

.zone-name {
    font-weight: 500;
    color: #303133;
}

.site-count {
    font-size: 12px;
    color: #909399;
    margin-left: 8px;
}

.node-actions {
    opacity: 0;
    transition: opacity 0.3s;
}

.custom-tree-node:hover .node-actions {
    opacity: 1;
}

.config-section {
    margin-bottom: 24px;
    background: white;
    padding: 20px;
    border-radius: 4px;
    border: 1px solid #ebeef5;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}

.section-title {
    margin: 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
}

.mt-2 {
    margin-top: 20px;
}

.mb-2 {
    margin-bottom: 16px;
}

.dialog-content {
    max-height: 500px;
    overflow-y: auto;
}

.dialog-footer {
    text-align: right;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
}

:deep(.el-tree-node__content) {
    height: 36px;
}

:deep(.el-tree-node.is-current > .el-tree-node__content) {
    background-color: #ecf5ff;
    color: #409eff;
}
</style>